﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Guoc.BigMall.Infrastructure;
using Dapper.DBContext;
using Guoc.BigMall.Domain.Entity;
using Guoc.BigMall.Infrastructure.Caching;
using Guoc.BigMall.WebService.Dto;
using Guoc.BigMall.WebService;

namespace Guoc.BigMall.Web.Services
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class TokenAuthorizeAttribute : AuthorizeAttribute
    {
        //IContextFacade _context;
        //IRoleFacade _roleFacade;
        ICacheManager _cache;
        ITokenService _tokenService;
        public TokenAuthorizeAttribute()
        {
            this._cache = Infrastructure.AppContext.Current.Resolve<ICacheManager>();
            _tokenService = Infrastructure.AppContext.Current.Resolve<ITokenService>();
            //this._roleFacade = Infrastructure.AppContext.Current.Resolve<IRoleFacade>();
        }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
                throw new ArgumentNullException("httpContext");

            var token = HttpContext.Current.Request.Headers["token"];
            return _tokenService.Validate(token);
           
        }



        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.Result = new JsonNetResult(ResultModel.Unauthorized())
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                ContentEncoding = System.Text.Encoding.UTF8,                 
            };
        }
    }
}